package org.shiro.demo.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.shiro.demo.dao.util.QueryCondition;
import org.shiro.demo.entity.FreeCollect;
import org.shiro.demo.entity.FreeInfo;
import org.shiro.demo.entity.OrderProp;
import org.shiro.demo.entity.ResponseResult;
import org.shiro.demo.entity.Ticket;
import org.shiro.demo.entity.User;
import org.shiro.demo.service.IBaseService;
import org.shiro.demo.service.IFreeInfoService;
import org.shiro.demo.util.UUIDCreator;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/freeticket")
public class FreeTicketController {

	@Resource(name = "baseService")
	private IBaseService baseService;

	@Resource(name = "freeInfoService")
	// 有缓存
	private IFreeInfoService freeInfoService;

	private User getCurrentUser() {
		// 设置订单主人为当前登陆的用户.
		Subject currentUser = SecurityUtils.getSubject();
		User customer = (User) currentUser.getPrincipal();
		return customer;
	}

	// -------------------------------------------免费代金券-------------------------------------------
	/**
	 * 关键点：只能add 一次。。所以需要一张 活动表 来记录 领取过的 人的情况。 表结构：n_free_collect
	 * 
	 * id;phone;ticket_uuid;create_time
	 * 
	 * 
	 */
	@RequestMapping(value = "/add")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles("customer")
	public ResponseResult add(int version) {
		ResponseResult rr = new ResponseResult();
		FreeInfo freeinfo = freeInfoService.get(version);
		if (freeinfo == null || !freeinfo.isUseful()) {
			rr.setInfo("不存此代金券");
			return rr;
		}
		User customer = getCurrentUser();
		// 不用判断金额，不用判断支付方式
		// if (money < 0) {
		// return new ResponseResult(0, " 金额小于0", null);
		// }
		// if (!payType.equals("tenpay") ) {// free ticket 只有 微信支付
		// return new ResponseResult(0, " 支付方式有误", null);
		// }
		/**
		 * 从数据库表n_free_collect 中找到已经存在的ticket
		 */
		List<QueryCondition> queryConditions = new ArrayList<QueryCondition>();
		queryConditions.add(new QueryCondition("phone", QueryCondition.EQ, customer.getPhone()));
		// 可以不写， 因为 以后活动都是单独做的。 做完一次活动， 就把数据删除了。
		// queryConditions.add(new QueryCondition("version", QueryCondition.EQ,
		// version ));
		FreeCollect freecollect = (FreeCollect) baseService.getSingleResult(FreeCollect.class, queryConditions);
		Ticket ticket = null;
		// 如果 存在， 查看是否已经付款。
		if (freecollect != null) {
			List<QueryCondition> queryConditions2 = new ArrayList<QueryCondition>();
			queryConditions2.add(new QueryCondition("uuid", QueryCondition.EQ, freecollect.getUuid()));
			ticket = (Ticket) baseService.getSingleResult(Ticket.class, queryConditions2);

			if (ticket.getOrderProp().getId() == 1L) {// 未付款，直接返回信息
				rr.setCode(1);
				rr.setObject(ticket);
				return rr;
			} else {// 已经付款，或者提货，或者取消了。。。
				rr.setCode(0);
				rr.setInfo("您已领取过了，不能重复领取");
				return rr;
			}
		}
		// 不存在。、说明没有 领取，先看下 份数 是不是被领完了。 没有就 生成新的ticket。
		List<QueryCondition> queryConditions3 = new ArrayList<QueryCondition>();
		queryConditions3.add(new QueryCondition("isPay", QueryCondition.EQ, false));
		int people = (int) baseService.getRecordCount(FreeCollect.class, queryConditions3);
		if (people >= freeinfo.getHowmany()) {// 已经领完了。
			rr.setCode(0);
			rr.setInfo("抱歉，免费代金券已领完了");
			return rr;
		}
		ticket = new Ticket();
		ticket.setUuid("t" + UUIDCreator.getShortUuid() + customer.getId() + version + "t");
		// 规则， 后面加上verison 跟t

		// 描述=>备注
		ticket.setDescription("这是一张免费的代金券");
		ticket.setUser(customer);
		// 下单时间即为此时此刻
		ticket.setPostTime(new Date());
		// 交易时间/付款时间此时未定
		ticket.setDealTime(null);
		ticket.setIsPay(false);// 默认未支付
		ticket.setIsBuffet(true);// 默认是自提
		ticket.setIsCancel(false);// 默认订单不是取消状态
		try {
			// 设置订单的初始状态
			OrderProp orderProp = new OrderProp();
			orderProp.setId(1L);
			orderProp.setStatus(1);
			ticket.setOrderProp(orderProp);
			// 设置uuid。。t开头+8位uuid+个人id。
			ticket.setMoney(freeinfo.getMoney());
			ticket.setDiscount(freeinfo.getDiscount());
			// 设置支付方式
			ticket.setPayType("tenpay");
			ticket.setDeliveryType("自提");
			ticket.setBufferInterval(0);// 代金券 默认当天提
			baseService.update(ticket);// 可能新建，可能更新

			// 将信息 写入 freeCollect..正常来说，应该用 事务的。。但是就算不用事务，也不会出错。
			FreeCollect collect = new FreeCollect();
			collect.setCreateTime(ticket.getPostTime());
			collect.setPhone(customer.getPhone());
			collect.setUuid(ticket.getUuid());
			collect.setVersion(version);
			baseService.save(collect);
		} catch (Exception e) {
			e.printStackTrace();
			return new ResponseResult(0, "下单失败,订单信息有误.", null);
		}
		return new ResponseResult(1, "下单成功", ticket);
	}

	@RequestMapping(value = "/clear")
	@ResponseBody
	public ResponseResult clear(int version) {
		ResponseResult rr = new ResponseResult();
		try {
			freeInfoService.delate(version);
			rr.setCode(1);
			return rr;
		} catch (Exception r) {
			r.printStackTrace();
			return rr;
		}
	}
}